import os
import sys

import click
from flask import Flask, render_template, request, flash, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column

WIN = sys.platform.startswith('win')
if WIN:  # 如果是 Windows 系统，使用三个斜线
    prefix = 'sqlite:///'
else:  # 否则使用四个斜线
    prefix = 'sqlite:////'

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭对模型修改的监控
app.config['SECRET_KEY'] = 'singlehe'
# 在扩展类实例化前加载配置
db = SQLAlchemy(app)


class User(db.Model):  # 表名将会是 user（自动生成，小写处理）
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    username: Mapped[str] = mapped_column(String(30), unique=True, nullable=False)


class Movie(db.Model):  # 表名将会是 movie
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    title: Mapped[str] = mapped_column(String(30), nullable=False)
    year: Mapped[str] = mapped_column(String(4), nullable=False)

    # 转换成字典的辅助方法
    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'year': self.year
        }


# name = 'SingleHe'
# movies = [
#     {'title': '肖申克的救赎', 'year': '1994'},
#     {'title': '霸王别姬', 'year': '1993'},
#     {'title': '阿甘正传', 'year': '1994'},
#     {'title': '泰坦尼克号', 'year': '1997'},
#     {'title': '千与千寻', 'year': '2001'},
#     {'title': '美丽人生', 'year': '1997'},
#     {'title': '这个杀手不太冷', 'year': '1994'},
#     {'title': '星际穿越', 'year': '2014'},
#     {'title': '盗梦空间', 'year': '2010'},
#     {'title': '楚门的世界', 'year': '1998'},
# ]
@app.cli.command()
def forge():
    """Generate fake data."""
    db.create_all()

    # 全局的两个变量移动到这个函数内
    name = '何盛国'
    movies = [
        {'title': '肖申克的救赎', 'year': '1994'},
        {'title': '霸王别姬', 'year': '1993'},
        {'title': '阿甘正传', 'year': '1994'},
        {'title': '泰坦尼克号', 'year': '1997'},
        {'title': '千与千寻', 'year': '2001'},
        {'title': '美丽人生', 'year': '1997'},
        {'title': '这个杀手不太冷', 'year': '1994'},
        {'title': '星际穿越', 'year': '2014'},
        {'title': '盗梦空间', 'year': '2010'},
        {'title': '楚门的世界', 'year': '1998'},
    ]

    user = User(username=name)
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year=m['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Done.')


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        title = request.form['title']
        year = request.form['year']
        if not title or not year or len(year) > 4 or len(title) > 30:
            flash('输入有误')
            return redirect(url_for('index'))
        movie = Movie(title=title, year=year)
        db.session.add(movie)
        db.session.commit()
        flash('新影片添加成功！')
        return redirect(url_for('index'))
    movies = Movie.query.all()
    return render_template('index.html', movies=movies)


@app.route('/movie/delete/<int:movie_id>')  # 限定只接受 POST 请求
def delete(movie_id):
    movie = Movie.query.get_or_404(movie_id)  # 获取电影记录
    db.session.delete(movie)  # 删除对应的记录
    db.session.commit()  # 提交数据库会话
    flash('影片信息删除成功！')
    return redirect(url_for('index'))  # 重定向回主页


@app.route('/movie/update/<int:movie_id>', methods=['GET', 'POST'])
def update(movie_id):
    movie = Movie.query.get_or_404(movie_id)  # 获取电影记录
    print(movie)
    if movie:
        return jsonify(movie.to_dict())
    else:
        return jsonify({'error': 'Movie not found'}), 404


@app.route('/movie/do_update', methods=['POST'])
def do_update():
    movie_id = int(request.form['movieID'])
    # 获取新记录
    title = request.form['newTitle']
    year = request.form['newYear']
    if not title or not year or len(year) != 4 or len(title) > 30:
        flash('影片信息输入有误！')
        return redirect(url_for('update', movie_id=movie_id))
    movie = Movie.query.get_or_404(movie_id)  # 获取电影记录
    movie.title = title
    movie.year = year
    db.session.commit()
    flash('影片信息更新成功！')
    return redirect(url_for('index'))


@app.context_processor
def inject_user():
    user = User.query.first()
    return dict(user=user)


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
